package com.farmlei.facereg.modules.recognition.service.impl;

import com.farmlei.facereg.common.utils.PropertiesUtils;
import com.farmlei.facereg.modules.face.AFR_FSDK_FACEMODEL;
import com.farmlei.facereg.modules.face.ASVLOFFSCREEN;
import com.farmlei.facereg.modules.face.FaceInfo;
import com.farmlei.facereg.modules.face.utils.ArcsoftUtil;
import com.farmlei.facereg.modules.recognition.entity.UserFaceFeature;
import com.farmlei.facereg.modules.recognition.mapper.UserFaceFeatureMapper;
import com.farmlei.facereg.modules.recognition.service.IUserFaceFeatureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.configuration.Configuration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * <p>
 * 人脸特征信息 服务实现类
 * </p>
 *
 * @author farmlei
 * @since 2018-10-05
 */
@Service
public class UserFaceFeatureServiceImpl extends ServiceImpl<UserFaceFeatureMapper, UserFaceFeature> implements IUserFaceFeatureService {
    @Resource
    private UserFaceFeatureMapper userFaceFeatureMapper;
    @Override
    public void saveFaceFeature(Long userId, String faceImg) throws Exception {
        Configuration config = PropertiesUtils.getConfig();
        String fileRoute = config.getString("fileRoute");
        String filePath = fileRoute.substring(0, fileRoute.indexOf("/")) + faceImg;

        BufferedImage img = ImageIO.read(new File(filePath));
        ASVLOFFSCREEN inputImg = ArcsoftUtil.changePic(img);
        FaceInfo[] faceInfosA = ArcsoftUtil.doFaceDetection(inputImg);
        if (faceInfosA.length < 1) {
            throw new Exception("无法获取人脸特征");
        }
        AFR_FSDK_FACEMODEL model = ArcsoftUtil.extractFRFeature(inputImg, faceInfosA[0]);
        byte[] faceModel = model.toByteArray();
        model.freeUnmanaged();// 销毁人脸模型

        UserFaceFeature userFaceFeature = new UserFaceFeature();
        userFaceFeature.setUserId(userId);
        userFaceFeature.setFaceFeature(faceModel);

        userFaceFeatureMapper.insert(userFaceFeature);
    }
}
